<template>
  <div class="page-table">
    <div class="page-filter">
      <div class="query">
        <el-form size="mini">
          <ad-datetime-range :options="false" @select="search" @search="search">
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.orderSubNo" placeholder="订单号" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.carName" placeholder="车辆名称" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.vin" placeholder="车牌/车架号" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.orderCreateUserName" placeholder="制单人" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.linkmanName" placeholder="委托联系人" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-input v-model="searchQuery.linkmanPhone" placeholder="联系电话" clearable/>
              </el-form-item>
            </el-col>
          </ad-datetime-range>
        </el-form>
      </div>
    </div>

    <div class="wrapper">
      <div class="left">
        <div class="top">
          <ad-table ref="order"
                    :data="orderList" v-loading="orderInitLoading" u-table :data-changes-scroll-top="orderIsScrollTop"
                    @row-click="orderSelectRow" @selection-change="orderSelectRows"
                    :searchQuery="orderSearchQuery" @search="orderGetInitList"
                    @sort-change="orderSortInitList" @filter-change="orderFilterInitList"
                    @table-body-scroll="orderGetMoreList" :height="tableHeight"  @cell-click="cellClick">
            <ad-table-column label="序号" type="index" ctype="index" fixed/>
            <ad-table-column label="运单号" prop="transportNo" searchable w="4c1f"/>
            <ad-table-column label="状态" prop="logisticsStatus" dictName="logistics_status" sortable filterable w="2c2f"/>
            <ad-table-column label="运单创建人" prop="createUserName" searchable w="4c2f" sortable/>
            <ad-table-column label="运单创建时间" prop="createTime" ctype="datetime" w="1f" sortable/>
            <ad-table-column label="运输方式" prop="transportType" dictName="transport_way" filterable w="4c1f"/>
            <ad-table-column label="路线" prop="line" ctype="line"/>
            <ad-table-column label="承运单位" prop="companyName" searchable w="7c1f"/>
            <ad-table-column label="司机姓名" prop="driverName" searchable w="4c1f"/>
            <ad-table-column label="司机电话" prop="driverPhone" searchable w="4c1f"/>
            <ad-table-column label="板车牌号" prop="licensePlateNumber" searchable w="4c1f"/>
            <ad-table-column label="应付运费" prop="driverFee" w="4c"/>
            <ad-table-column label="司机欠返" prop="backReturnFee" w="4c"/>
            <ad-table-column label="车厢号" prop="compartmentNo" w="4c2f"/>
            <ad-table-column label="票号" prop="ticketNo" w="4c2f"/>
<!--            <el-table-column fixed="right" label="操作" width="80">-->
<!--              <template slot-scope="scope">-->
<!--                <el-button @click.stop="goBack(scope.row)" type="danger" size="mini">回退</el-button>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <ad-table-column width="auto"/>
            <!--        <ad-table-column label="最近一次跟踪时间" ctype="datetime" prop="createTime" w="1f"/>-->
            <!--        <ad-table-column label="跟踪位置" prop="lastLogisticsAddress" w="4c1f"/>-->
            <!--        <ad-table-column label="跟踪人" prop="lastLogisticsUserName" searchable w="4c1f"/>-->
            <!--        <ad-table-column label="跟踪备注" prop="remark" ctype="remark"/>-->
          </ad-table>
        </div>

        <div class="divider-h"></div>

        <!--      底部弹框-->
        <el-drawer
          size="35%"
          :visible.sync="drawer"
          direction="btt"
          :with-header="false">
        <div id="bottom" class="bottom">
          <div class="bottom-title-bar">
            <h2>运单号：{{curTransportNo}}</h2>
          </div>
          <div class="bottom-content">
            <div class="bottom-left">
              <ad-table ref="order" excess-rows="50"
                        :data="detailListFilter" v-loading="detailInitLoading" u-table :data-changes-scroll-top="detailIsScrollTop"
                        @row-click="detailSelectRow" @selection-change="detailSelectRows"
                        :span-method="objectSpanMethod" :height="bottomTabHeight">
                <ad-table-column label="操作" prop="levelId" w="3c2f">
                  <template slot-scope="{row}">
                    <slot :row="row">
                      <div class="op" style="justify-content: center">
                        <span v-if="row.reserved==1">留板信息</span>
                        <el-button v-else-if="row.levelType == 2 && !row.hasArrived" type="text" class="op-btn" @click="openArriveAdder(row)">确认到达</el-button>
                      </div>
                      <!--                  <el-link v-if="!row.levelFileUrl" @click="createWaybill(row)">生成发运单</el-link>-->
                      <!--                  <el-link v-else :href="row.levelFileUrl" target="_blank">查看发运单</el-link>-->
                    </slot>
                  </template>
                </ad-table-column>
                            <el-table-column  label="是否回退" width="80">
                              <template slot-scope="scope">
                                <el-button @click.stop="goBack(scope.row)" type="danger" size="mini"  v-if="scope.row.hasArrived">回退</el-button>
                              </template>
                            </el-table-column>
                <ad-table-column label="路线">
                  <template v-slot="{row}">
                    <template v-if="row.levelStartCode">
                      <value :model="row" prop="levelStartCode" type="city"/> - <value :model="row" prop="levelDestinationCode" type="city"/>
                    </template>
                    <template v-else>-</template>
                  </template>
                </ad-table-column>
                <ad-table-column label="发运人" prop="createUserName" w="3c2f"/>
                <ad-table-column label="发运时间" prop="createTime" ctype="datetime" w="1f"/>
                <ad-table-column label="交付方式" prop="levelType" dictName="delivery_type" w="3c2f"/>
                <ad-table-column label="接车联系人" prop="levelReceiveUser" w="3c2f"/>
                <ad-table-column label="接车联系人电话" prop="levelReceivePhone" ctype="phone-2f"/>
                <ad-table-column label="接车地址" prop="levelReceiveAddress" ctype="address-2f"/>
                <ad-table-column label="订单编号" prop="orderSubNo" ctype="orderNo" w="3c2f"/>
                <ad-table-column label="出发地" prop="orderStartCode" ctype="city"/>
                <ad-table-column label="目的地" prop="orderDestinationCode" ctype="city"/>
                <ad-table-column label="车辆名称" prop="orderCarName" w="4c2f"/>
                <ad-table-column label="车架号" prop="orderVin" ctype="vin-2f"/>
                <ad-table-column label="制单人" prop="orderCreateUserName" w="3c2f"/>
                <ad-table-column label="收货人" prop="orderConsigneeName" w="3c2f"/>
                <ad-table-column label="联系电话" prop="orderConsigneePhone" ctype="phone-2f"/>
                <ad-table-column label="承运费用" prop="cost" w="3c2f"/>
                <ad-table-column label="到付金额" prop="orderDeliveryPayFee" w="3c2f"/>
                <ad-table-column label="是否代收" prop="hasCollection" dictName="yes_or_no" w="3c2f"/>
              </ad-table>
            </div>
          </div>
        </div>
        </el-drawer>

      </div>

      <div class="divider-v"></div>

      <div class="right">
        <div class="title-bar">
          <h3>更新位置</h3>
          <div class="op">
            <el-button size="mini" type="primary" plain :disabled="!orderSelectedRowId" :loading="recordSaving" @click="updateLocation">更新位置</el-button>
          </div>
        </div>
        <div class="content">
          <el-form :model="recordForm" ref="recordForm" size="mini" class="ad-form" inline label-width="auto" label-position="right">
            <el-form-item label="告知用户：">
              <el-checkbox v-model="recordForm.appShow" :true-label="1" :false-label="0">将位置更新到用户app上</el-checkbox>
            </el-form-item>
            <el-form-item label="当前位置：" prop="arriveLocation" :rules="[{required: true, message: '请选择'}]">
              <el-input v-model="recordForm.arriveLocation" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="跟踪备注：" prop="remark">
              <el-input v-model="recordForm.remark" placeholder="请输入"/>
            </el-form-item>
          </el-form>
          <h4>位置更新记录</h4>
          <el-scrollbar class="record">
            <div class="step" v-for="(record, index) in recordList" :key="index">
              <div class="info">
                <div class="icon-dot"></div>
                <div class="value">
                  <div><value :model="record" prop="createTime" type="datetime"/></div>
                  <div><value :model="record" prop="arriveLocation" show-overflow-tooltip/></div>
                </div>
              </div>
              <div class="other">
                <div class="icon-line"></div>
                <div v-if="index < recordList.length - 1" class="other-content">
                  <div class="item">
                    <div class="label">跟踪备注：</div><div class="value"><value :model="record" prop="remark"/></div>
                  </div>
                  <div class="item">
                    <div class="label">跟踪人：</div><div class="value"><value :model="record" prop="createUserName"/></div>
                    <div v-if="record.appShow" v-html="'　已通知用户'" style="color: #ff4d4f"></div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>

    <el-dialog title="确认到达" :visible.sync="arriveAdder.visible" custom-class="ad-dialog" width="1100px">
      <arrive-adder :id="arriveAdder.levelId" :visible.sync="arriveAdder.visible" @saved="detailSaved"/>
    </el-dialog>
  </div>
</template>

<script>
import Value from '@/components/AdValue'
import AdDatetimeRange from '@/components/AdDateTimeRange'
import AdTable from '@/components/AdTable'
import AdTableColumn from '@/components/AdTable/AdTableColumn'
import arriveAdder from './dialog/arriveAdder'
import dateRange from '@/utils/dateRange'
import adTable from '@/mixins/adTable/index'
import { getList as orderApiGetList  } from '@/api/logistics'
import { getList as detailApiGetList  } from '@/api/logistics/detail'
import {
  getList as getRecordList,
  update as updateRecordList,
  returnTransport,
  finishReLevel
} from '@/api/logistics/record'
import api from '@/api/pick/wait'

export default {
  name: 'logistics-index',
  components: { Value, AdDatetimeRange, AdTable, AdTableColumn, arriveAdder },
  dicts: ['delivery_type','yes_or_no','logistics_status','transport_way'],
  mixins: [adTable([
    {name: 'order'},
    {name: 'detail', parent: 'order'},
  ])],
  data() {
    return {
      drawer: false,
      tableHeight: 0,
      bottomTabHeight: 0,
      searchQuery: {
        beginSearchTime: '',
        endSearchTime: ''
      },
      recordSaving: false,
      recordForm: {
        appShow: 0,
        arriveLocation: '',
        remark: ''
      },
      recordList: [],
      arriveAdder: {
        visible: false,
        levelId: ''
      }
    }
  },
  created() {
    setTimeout(() => {
      // this.tableHeight = document.documentElement.clientHeight - document.getElementById('bottom').offsetHeight - 140;
      this.tableHeight = document.documentElement.clientHeight - 143;
      this.bottomTabHeight = document.getElementById('bottom').offsetHeight - 38
    })
    this.orderGetInitList()
  },
  computed: {
    detailListFilter() {
      return this.detailList.filter(row => row.levelHasArrived != 1)
    },
    curTransportNo() {
      if (this.orderSelectedRow) {
        if (this.orderSelectedRow._row) {
          return this.orderSelectedRow._row.transportNo
        } else {
          return this.orderSelectedRow.transportNo
        }
      } else {
        return '-'
      }
    }
  },
  methods: { orderApiGetList, detailApiGetList,
    search(times) {
      this.searchQuery.beginSearchTime = times.beginSearchTime
      this.searchQuery.endSearchTime = times.endSearchTime
      this.orderGetInitList()
    },
    goBack (row) {
      let self = this
      self.$confirm('是否确定回退?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        finishReLevel(row.orderId).then(res => {
          if (res.code == 0) {
            self.$notify({
              title: '提示',
              message: '回退成功！',
              position: 'bottom-right',
              type: 'success'
            })
          }
        })
      }).catch(() => {
      })
    },
    orderAfterSelectRow() {
      this.detailGetInitList()
      this.recordGetList()
      this.$refs.recordForm.resetFields()
    },
    detailSaved() {
      this.detailGetInitList()
    },
    cellClick(){
      this.drawer = true
    },
    updateLocation() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          this.$confirm('确定更新位置吗？','更新位置').then(() => {
            this.recordSaving = true
            updateRecordList({transportId: this.orderSelectedRowId, ...this.recordForm})
              .then(() => {
                this.orderSelectedRow.logisticsStatus = 1
                this.recordGetList()
                this.$refs.recordForm.resetFields()
              })
              .finally(() => this.recordSaving = false)
          }).catch(err => {})
        }
      })
    },
    openArriveAdder(row) {
      setTimeout(() => {
        this.arriveAdder.levelId = row.levelId
        this.arriveAdder.visible = true
      })
    },
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      let self = this;
      if (column.property === 'levelId') {
        if (rowIndex === 0 || row.levelId != self.detailListFilter[rowIndex - 1].levelId) {
          let rowspan = 0;
          self.detailList.forEach(element => {
            if (element.levelId === row.levelId) {
              rowspan++;
            }
          });
          return [rowspan, 1];
        } else {
          return [0, 0];
        }
      }
    },
    recordGetList() {
      getRecordList(this.orderSelectedRowId).then(res => {
        this.recordList = res.data.reverse()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox__label { font-size: 12px; font-weight: normal; }
.wrapper { display: flex;
  .left { flex: 1; width: 0; }
  .divider-v { width: 4px; background: #CFE2F3; }
  .right { display: flex; width: 340px; box-sizing: border-box; border: 1px solid #e3e3e3; flex-direction: column; border-left: 1px solid #e3e3e3;
    .title-bar { display: flex; height: 36px; padding: 0 16px; align-items: center; background: #f3f3f3;
      h3 { font-size: 12px; font-weight: bold; }
      .op { margin-left: auto; }}
    .content { display: flex; flex: 1; padding: 15px; flex-direction: column;
      h4 { margin: 2px 0 4px 0; font-size: 12px; font-weight: bold; }
      .record { flex-grow: 1; height: 0; padding: 12px; border: 1px solid #e3e3e3; font-size: 12px;
        .step { box-sizing: border-box;
          .info { display: flex; line-height: 14px;
            .icon-dot { width: 14px; height: 14px; min-width: 14px; margin-right: 14px; box-sizing: border-box; border: 2px solid #1890FF; border-radius: 7px; }
            .value { display: flex; flex: 1;
              &>*:first-child { margin-right: 10px; white-space: nowrap; }
              &>*:last-child { display: flex; flex: 1; width: 0; overflow: hidden; white-space: nowrap; }}}
          .other { display: flex;
            .icon-line { display: flex; width: 14px; min-width: 14px; min-height: 20px; margin-right: 14px; justify-content: center;
              &:after { content: ''; display: block; width: 2px; height: 100%; background: #dfdfdf; }}
            .other-content { padding-bottom: 14px; }
            .item { display: flex; flex: 1; margin-top: 2px; color: #a1a1a1;
              &:first-child { margin-top: 4px; }
              .label { white-space: nowrap; }}}
          &:last-child .icon-line:after { background: #fff; }}}}}
}
::v-deep .ad-dialog .el-dialog__body { padding: 0; }
.top { border: 1px solid #e3e3e3; border-bottom: none; }
.divider-h { height: 4px; border: 1px solid #e3e3e3; border-bottom: 1px solid #4da7fa; border-top: none; background: rgba(77,167,250, 0.2); }
.bottom { display: flex; height: 35vh; min-height: 290px; flex-direction: column; border: 1px solid #e3e3e3; border-top: none;
  .bottom-title-bar { display: flex; line-height: 36px; background: #f5f5f5; border-bottom: 1px solid #e3e3e3; padding-left: 10px;
    h2 { font-size: 12px; font-weight: bold; }}
  .bottom-content { display: flex; flex: 1;
    .bottom-left { flex: 1; width: 0; border-right: 1px solid #e3e3e3; }
    .bottom-right {}}}
</style>